<?php 

/***
 * This page is accessed via an AJAX call to manipulate News Data, ie
 * deleting, moving, etc.
 */

// ensure this file is only executed once we have been logged in
require_once("../accesscheck.php");
include_once('../utils/page_list_renderer.php');
kan_import('PageManager');

$pm = new PageManager();

if( isset($_POST['action']) ) {
	$action = $_POST['action'];
	
	switch($action) {
	
		case 'add_page':
			$page = $pm->createPage();
			//header("Location: ../pages.php");
			
			//echo $page->toJSON();
			listPages( array($page) );
			break;
			
		case 'update_page':
			$page = $pm->updatePage();
			//header("Location: ../pages.php");
			echo $page->toJSON();
			break;
			
		case 'delete_pages':
			$pm->deletePages( explode(",",$_POST['ids']) );
			break;
			
		case 'load_page':
			$page_id = intval($_POST['page_id']);
			$page = $pm->getPage($page_id);
			
			echo $page->toJSON();
			break;
			
		case 'publish':
		case 'unpublish':
			$id = $_POST['id'];
			$publish = $_POST['action'] == "publish" ? '1' : '0';
			
			$page = new Page($id);
			$page->setData('Published',$publish);
			$page->save();
			break;
		
		case 'load_homepage':
			include('../forms/pages_home_form.php');
			break;
			
		case 'update_homepage':
			kan_import('SitesManager');
			$sm = new SitesManager();
			$sm->updateSiteHomePageContent();
			
			//header("Location: ../pages.php");
			break;
			
		case 'load_footer':
			include('../forms/pages_footer_form.php');
			break;
			
		case 'load_editor':
			include('../forms/pages_form.php');
			break;
			
		case 'update_footer':
			kan_import('SitesManager');
			$sm = new SitesManager();
			$sm->updateSiteFooterContent();
			
			//header("Location: ../pages.php");
			break;
			
		case 'load_parent_page_options':
			echo '
				<option value="">No Parent [Menu Level Page]</option>
                <option value="">---------------------------</option>';
                    
				function printPageOptions($page_data, $level = 0) {
					global $edit_page;
					
					foreach($page_data as $data) {
						$dashes = str_repeat("--",$level);
						
						$selected = isset($edit_page) && $edit_page->getParentID() == $data['id'] ? 'selected="selected"' : "";
						echo "<option value='" . $data['id'] . "' $selected>" . $dashes . " " . $data['PageName'] . "</option>";
						
						if( isset($data['children']) ) {
							printPageOptions($data['children'], $l = $level + 1);	
						}
					}
				}
				
				$parent_pages = $pm->getAdjacencyTree()->getFullNodes( array("id","PageName","PageDescription") ); 
				printPageOptions($parent_pages);
			break;
		
		case 'show_sub_pages':
			$parent_id = intval($_POST['parent_id']);
			$pages = $pm->getPages( array("parent" => $parent_id) );
			
			listPages($pages);
			break;
		
	}
}
?>